<template>
  <div class="expressModal">
    <a-drawer :title="title" placement="right" :closable="false" :visible="visible" @close="onClose" width="1000">
      <!-- 主体内容 -->
      <div class="expressModal-body">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          labelAlign="right"
          layout="inline"
        >
          <DescTitle text="基本信息" />
          <!-- 表单区域 -->
          <template style="display:flex;flex-wrap: wrap;">
            <!-- 项目名称 -->
            <a-form-model-item ref="projectName" label="项目名称" prop="projectName" style="width:46%;height:65px;">
              <a-input
                :disabled="isAdd == 'select'"
                v-model="form.projectName"
                placeholder="请输入项目名称"
                @blur="
                  () => {
                    $refs.projectName.onFieldBlur()
                  }
                "
                :maxLength="128"
              />
            </a-form-model-item>
            <!-- 客户 -->
            <a-form-model-item ref="customerCode" label="客户" prop="customerCode" style="width:46%;height:65px;">
              <a-select
                style="width: 100%"
                show-search
                :disabled="isAdd == 'select'"
                :filter-option="filterOption"
                @change="customerChange"
                v-model="form.customerCodes"
                placeholder="请选择客户"
              >
                <a-select-option :key="index" v-for="(item, index) in customerList" :value="item.customerCode">
                  {{ item.customerName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 货主 -->
            <a-form-model-item ref="ownerCode" label="货主" prop="ownerCode" style="width:46%;height:65px;">
              <a-select
                style="width: 100%"
                show-search
                :disabled="isAdd == 'select'"
                :filter-option="filterOption"
                @change="handleChange"
                v-model="form.ownerCode"
                mode="multiple"
                :maxTagCount="2"
                placeholder="请选择货主"
              >
                <a-select-option :key="index" v-for="(item, index) in ownerList" :value="item.ownerCode">
                  {{ item.ownerName }}
                </a-select-option>
                <a-select-option value="b-other">
                  其他
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 物流公司 -->
            <a-form-model-item
              ref="logisticsCompanyCode"
              label="物流公司"
              prop="logisticsCompanyCode"
              style="width:46%;height:65px;"
            >
              <a-select
                style="width: 100%"
                show-search
                :disabled="isAdd == 'select'"
                :filter-option="filterOption"
                @change="handleLogisticsChange"
                v-model="form.logisticsCompanyCode"
                mode="multiple"
                :maxTagCount="2"
                placeholder="请选择物流公司"
              >
                <a-select-option :key="index" v-for="(item, index) in logisticsCompanyList" :value="item.companyCode">
                  {{ item.companyCode }}
                </a-select-option>
                <a-select-option value="b-other">
                  其他
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </template>
          <!-- 备注 -->
          <div style="width:100%;height:85px;position:relative;">
            <span style="padding-left:60px;position:absolute;top:0px;">项目备注：</span>
            <a-textarea
              :disabled="isAdd == 'select'"
              v-model="form.remark"
              placeholder="请输入项目备注"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width:745px;height:85px;margin-left:131px;"
              :maxLength="1024"
            />
          </div>
          <DescTitle text="规则配置" style="margin-top:15px" />
        </a-form-model>
        <!-- 循环部分 -->
        <template style="margin-bottom:30px">
          <div class="inputBox" :key="index" v-for="(item, index) in RuleDetailInfo">
            <!-- 加价名称 -->
            <div class="itemBox">
              <span class="text"> <span class="xing">* </span>加价名称： </span>
              <a-input
                :disabled="isAdd == 'select'"
                class="inputItem"
                v-model="item.markupName"
                placeholder="请输入加价名称"
              />
            </div>
            <!-- 地区 -->
            <div class="itemBox">
              <span class="text" style="transform: translateY(-10px);"><span class="xing">* </span>地区：</span>
              <!-- :load-data="onLoadData" -->
              <!-- :height="233" -->
              <!-- treeDefaultExpandAll -->
              <!-- treeDefaultExpandAll -->
              <!-- :treeDefaultExpandAll="true" -->
              <a-tree-select
                :disabled="isAdd == 'select'"
                :load-data="onLoadData"
                v-model="item.demoInfo"
                tree-data-simple-mode
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                class="inputItem"
                tree-checkable
                :tree-data="treeData2"
                :replaceFields="{
                  children: 'child',
                  title: 'name',
                  key: 'areaId',
                  value: 'areaId'
                }"
                :show-checked-strategy="SHOW_PARENT"
                placeholder="请选择地区"
                @change="
                  keys => {
                    change(keys, index)
                  }
                "
              />
            </div>
            <!-- 加价方式 -->
            <div class="itemBox">
              <span class="text"><span class="xing">* </span>加价方式：</span>
              <a-select
                :disabled="isAdd == 'select'"
                placeholder="请选择加价方式"
                show-search
                :filter-option="filterOption"
                class="inputItem"
                v-model="item.markupWay"
              >
                <a-select-option value="fixed">
                  按固定值
                </a-select-option>
                <a-select-option value="rate">
                  按百分比
                </a-select-option>
              </a-select>
            </div>
            <!-- 价格 -->
            <div class="itemBox" v-show="item.markupWay === 'fixed'">
              <span class="text"><span class="xing">* </span>价格(元)：</span>
              <a-input-number
                :disabled="isAdd == 'select'"
                v-model="item.markupValue"
                class="inputItem"
                :min="0"
                :max="2147483647"
                :precision="2"
                placeholder="请输入规则价格"
              />
            </div>
            <!-- 百分数 -->
            <div class="itemBox" v-show="item.markupWay === 'rate'">
              <span class="text"><span class="xing">* </span>百分数：</span>
              <a-input-number
                :disabled="isAdd == 'select'"
                v-model="item.proportion"
                class="inputItem"
                :min="0"
                :max="100"
                :precision="0"
                placeholder="请输入规则价格"
              />
              <span style="margin-left: 5px;">%</span>
            </div>
            <div class="itemBox">
              <span class="text"><span class="xing">* </span>时间：</span>
              <!-- @ok="billTimeOk" -->
              <a-range-picker
                :disabled="isAdd == 'select'"
                v-model="item.time"
                format="YYYY-MM-DD HH:mm:ss"
                :placeholder="['Start Time', 'End Time']"
                @change="
                  (date, dataString) => {
                    editChange(date, dataString, index)
                  }
                "
                class="inputItem"
                :show-time="{
                  format: 'HH:mm:ss',
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                }"
              />
            </div>
            <RuleBtn
              :isDel="RuleDetailInfo.length > 1"
              :disable="isAdd == 'select'"
              @add="addRule"
              @del="delRule(index)"
            />
          </div>
        </template>
      </div>
      <!-- 保存按钮 -->
      <p :style="saveStyl" v-if="isAdd !== 'select'">
        <a-button type="primary" @click="onSubmit">
          保存
        </a-button>
      </p>
    </a-drawer>
  </div>
</template>

<script>
import moment from 'moment'
import { getOwnerName, getLogisticsList } from '@/api/api'
import DescTitle from '@/components/base/descTitle'
import RuleBtn from '@/components/base/ruleBtn'
import { TreeSelect } from 'ant-design-vue'
import { getTreeData, onLoadData } from '@/utils/util'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '创建公司快递加价规则'
    },
    customerList: {
      type: Array,
      default: () => []
    },
    whCode: {
      type: String,
      default: ''
    }
  },
  components: {
    DescTitle,
    RuleBtn
  },
  data() {
    return {
      isAdd: 'add',
      value1: undefined, //选中地区树数据
      SHOW_PARENT,
      treeData2: [
        {
          id: '11000000',
          areaId: '11000000',
          name: '全国',
          province: '',
          city: '',
          area: '',
          town: ''
        }
      ],
      placement: 'right', //抽屉打开方式
      dateFormat: 'YYYY-MM-DD HH:mm:ss', //日期格式
      precision: 2, //保留几位小数
      labelCol: { span: 7 },
      wrapperCol: { span: 16 },
      validStatus: true, // 当前表单验证状态，true表示成功，false表示失败
      form: {
        // 表单数据
        projectName: undefined, //项目名称
        customerCode: undefined, //客户编码
        customerCodes: [], //客户编码
        ownerCode: undefined, //货主编码
        logisticsCompanyCode: undefined, //快递公司编码
        remark: undefined //备注
      },
      rules: {
        // 校验规则
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'change' }],
        customerCodes: [{ required: true, message: '请选择客户', trigger: 'change' }],
        ownerCode: [{ required: true, message: '请选择货主', trigger: 'change' }],
        logisticsCompanyCode: [{ required: true, message: '请选择快递公司', trigger: 'change' }]
      },
      RuleDetailInfo: [
        {
          id: '',
          markupName: '',
          markupWay: undefined,
          markupValue: '',
          proportion: '',
          time: [],
          timeBegin: '',
          timeEnd: '',
          sortNo: '',
          demoInfo: []
        }
      ],
      ownerList: [
        // 货主列表
      ],
      logisticsCompanyList: [
        // // 快递公司列表
      ]
    }
  },
  computed: {
    saveStyl() {
      return {
        position: 'absolute',
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e8e8e8',
        padding: '10px 16px',
        textAlign: 'right',
        left: 0,
        background: '#fff',
        borderRadius: '0 0 4px 4px',
        margin: 0,
        textAlign: 'center'
      }
    }
  },
  model: {
    prop: 'visible',
    event: 'onClose'
  },
  created() {
    this.$bus.$on('isAdd', (tag, data) => {
      this.isAdd = tag
      if (!!data) {
        // 修改or查看
        console.log(111)
        this.getOwnerName(data.customerCode)
        this.getLogisticsList()
        if (tag === 'edit') {
          //   let obj = {
          //     id: '1514420211279769601',
          //     optimistic: 0,
          //     organizeId: '1459090536851894273',
          //     whCode: 'FSN',
          //     projectName: '123',
          //     customerCode: 'FSN',
          //     ownerCode: 'FSN@FSN',
          //     companyCode: 'FSN@SFBK,FSN@SFTK',
          //     remark: '3423',
          //     ruleType: 'CUST',
          //     delFlag: 0,
          //     extendOne: null,
          //     createBy: 'admin',
          //     createTime: '2022-04-14 09:48:10',
          //     updateBy: null,
          //     updateTime: null,

          //   }
          //   this.form = data
          this.RuleDetailInfo = data.ruleDetailInfo
        }
      } else {
        // 新增
        if (this.validStatus === false) {
          this.$refs.ruleForm.resetFields()
        }
        this.form.projectName = undefined
        this.form.customerCode = undefined
        this.form.ownerCode = undefined
        this.form.logisticsCompanyCode = undefined
        this.form.remark = undefined
        this.RuleDetailInfo = [
          {
            markupName: '',
            markupWay: undefined,
            markupValue: '',
            proportion: '',
            time: [],
            timeBegin: '',
            timeEnd: '',
            sortNo: '',
            demoInfo: []
          }
        ]
        // }
      }
      // this.isSelect = console.log('测试EventBus', tag, data)
      // if (this.validStatus === false) {
      //   this.$refs.ruleForm.resetFields()
      // }
    })
  },
  methods: {
    // 提取地区树数据
    change(keys, index) {
      this.$set(this.RuleDetailInfo[index], 'areaInfo', getTreeData(keys, this, 'areaId'))
    },
    // 异步加载地区树
    async onLoadData(treeNode) {
      await onLoadData(treeNode, this)
    },
    // 关闭抽屉
    onClose(e) {
      this.$emit('onClose', e)
    },
    // 提交数据
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.validStatus = true
          this.$emit('onSubmit', this.form, this.RuleDetailInfo, this.isAdd)
        } else {
          return false
        }
      })
    },
    moment,
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 选择客户change
    customerChange(e) {
      // if(this.form.ownerCode){
      this.form.ownerCode = undefined
      // }
      if (this.form.customerCode) {
        this.getOwnerName()
        this.getLogisticsList()
      }
    },
    // 获取快递公司
    getLogisticsList() {
      let params = {
        whCode: this.whCode,
        customerCode: this.form.customerCode
      }
      getLogisticsList(params).then(res => {
        if (res.success) {
          this.logisticsCompanyList = res.result.records
        }
      })
    },
    // 获取货主名称列表
    getOwnerName(code) {
      let params = {
        whCode: this.whCode,
        customerCode: code ? code : this.form.customerCode
      }
      getOwnerName(params).then(res => {
        if (res.success) {
          this.ownerList = res.result
        } else {
          this.$message.warning(res.message, 6)
        }
      })
    },
    // 选择货主change
    handleChange(e) {
      console.log(e)
    },
    // 选择物流公司change
    handleLogisticsChange(e) {
      console.log(e)
    },
    // 修改时间
    editChange(value, dateString, index) {
      this.$set(this.RuleDetailInfo[index], 'time', value)
      this.$set(this.RuleDetailInfo[index], 'timeBegin', dateString[0])
      this.$set(this.RuleDetailInfo[index], 'timeEnd', dateString[1])
    },
    // 添加规则
    addRule() {
      this.RuleDetailInfo.push({
        markupName: '',
        markupWay: undefined,
        markupValue: '',
        proportion: '',
        time: [],
        timeBegin: '',
        timeEnd: '',
        sortNo: '',
        areaInfo: []
      })
    },
    delRule(index) {
      this.RuleDetailInfo.splice(index, 1)
    }
  }
}
</script>
<style lang="less" scoped>
.expressModal-body {
  margin-bottom: 30px;
  .inputBox {
    margin-left: 20px;
    display: flex;
    flex-wrap: wrap;
    .itemBox {
      width: 46%;
      height: 50px;
      margin-right: 26px;
      .text {
        text-align: end;
        padding-left: 28px;
        display: inline-block;
        width: 110px;
        .xing {
          color: red;
          font-weight: bolder;
        }
      }
      .inputItem {
        width: 295px !important;
      }
    }
  }
}
</style>
<style lang="less">
.expressModal-body .ant-form-inline .ant-form-item-with-help {
  margin-bottom: 0;
}
.expressModal-body .ant-select-selection--multiple {
  max-height: 32px;
  overflow-y: overlay;
}
</style>
